package com.sdp.wx.task;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sdp.right.cron.ScheduledOfTask;
import com.sdp.right.websocket.dto.MessageInfo;
import com.sdp.right.websocket.server.MessageWebsocketServer;
import com.sdp.wx.controller.WxSysConfigController;
import com.sdp.wx.db.wx_contract.entity.WxContract;
import com.sdp.wx.db.wx_contract.service.IWxContractService;
import com.sdp.wx.utils.WxConstants;

@Component
public class ContractExpireTask implements ScheduledOfTask{
	
	@Autowired
	private WxSysConfigController wxSysConfigController;
	
	@Autowired
	private IWxContractService iWxContractService;
	
	@Autowired
	private MessageWebsocketServer messageWebsocketServer;

	@Override
	public void execute() {
		
		Map<String, Map<String, String>> empClientIdMap = MessageWebsocketServer.getEmpClientIdMap();
		if(empClientIdMap==null || empClientIdMap.size()==0) {
			return;
		}
		
		String difDay = wxSysConfigController.getSysConfigParamValByCode(WxConstants.参数配置_轮式装备小修合同到期提前天数.getCode());
		if(StringUtils.isEmpty(difDay)) {
			difDay="30";
		}
		LambdaQueryWrapper<WxContract> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(WxContract::getContractType, WxConstants.轮式装备小修合同.getCode());
		queryWrapper.le(WxContract::getContractEt, LocalDate.now());
		queryWrapper.ge(WxContract::getContractEt, LocalDate.now().plusDays(0-Long.valueOf(difDay)));
		queryWrapper.eq(WxContract::getApprovalState, WxConstants.流程审批状态_审批通过.getCode());
		
		List<WxContract> list = iWxContractService.list(queryWrapper);
		if(list ==null || list.size()==0) {
			return;
		}
		StringBuffer sbf = new StringBuffer("将要到期的合同：");
		for(WxContract contract : list) {
			sbf.append(contract.getContractCode());
			sbf.append(",");
		}
		sbf.deleteCharAt(sbf.length()-1);
		for (Entry<String, Map<String, String>> entry : empClientIdMap.entrySet()) {
			MessageInfo messageInfo = new MessageInfo();
			messageInfo.setData(sbf.toString());
			messageInfo.setEmpNo(entry.getKey());
			messageInfo.setType(WxConstants.websocket轮式装备合同到期提醒.getCode());
			messageWebsocketServer.sendMessage(messageInfo);
		}
		
	}

}
